package br.com.dfr.sgc.persistence;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import br.com.dfr.sgc.entity.Usuario;
import br.com.dfr.sgc.enumeration.Papel;
import br.com.dfr.sgc.util.HibernateUtil;

public class UsuarioDao {
	private Session session;
	private Transaction t;

	public UsuarioDao() {
		session = HibernateUtil.getSession();
	}

	public Usuario procura(String matricula) {
		Criteria c = session.createCriteria(Usuario.class);
		c.add(Restrictions.ilike("matricula", matricula, MatchMode.ANYWHERE));
		c.addOrder(Order.asc("nome"));
		Usuario usuario = (Usuario) c.uniqueResult();

		return usuario;
	}

	@SuppressWarnings("unchecked")
	public List<Usuario> buscaTodosTecnicos() {
		Criteria c = this.session.createCriteria(Usuario.class);
		c.add(Restrictions.or(Restrictions.like("papel", Papel.TECNICO),
				Restrictions.like("papel", Papel.ADMINISTRADOR)));
		c.addOrder(Order.asc("matricula"));
		return c.list();
	}

	@SuppressWarnings("unchecked")
	public List<Usuario> buscaTodosUsuarios() {
		Criteria c = this.session.createCriteria(Usuario.class);
		c.add(Restrictions.like("papel", Papel.USUARIO));
		c.addOrder(Order.asc("matricula"));
		return c.list();
	}

	public void insere(Usuario usuario) {
		try {
			t = session.beginTransaction();
			session.save(usuario);
			t.commit();
		} catch (Exception e) {
			t.rollback();
			System.out.println("Erro ao inserir! " + e.getMessage());
		}
	}

	public void atualiza(Usuario usuario) {
		try {
			t = session.beginTransaction();
			session.update(usuario);
			t.commit();
		} catch (Exception e) {
			t.rollback();
			System.out.println("Erro ao atualizar! " + e.getMessage());
		}
	}

	public void deleta(Usuario usuario) {
		try {
			t = session.beginTransaction();
			session.delete(usuario);
			t.commit();
		} catch (Exception e) {
			t.rollback();
			System.out.println("Erro ao deletar! " + e.getMessage());
		}
	}

}
